<template>
  <div class="address-container">
    <nav-bar>
      <div class="left" slot="left"  @click="goBack()">
        <i class="iconfont icon-fanhui"></i>
      </div>
      <div slot="center">用户地址</div>
      <div slot="right" class="delete-icon" @click="deleteAddress()"><van-icon size="20"  name="delete-o" /></div>
    </nav-bar>
    <div class="address-content">
      <van-address-list
          v-model="chosenAddressId"
          :list="list"
          switchable
          default-tag-text="常用地址"
          @add="addAddress()"
          @edit="onEdit"
      />
    </div>
  </div>
</template>

<script>
import NavBar from '../../components/nav-bar/Nav-Bar'
import {Toast,Dialog} from 'vant'
import {getAddressList,deleteAddress} from "../../api/profile/profile";
export default {
  name: "AddressList",
  components:{
    NavBar,
  },
  data() {
    return {
      chosenAddressId:'1',
      list: [],
      oldList:[]
    };
  },
  mounted() {
    this.getAddressListData()
  },

  methods: {
    addAddress() {
      // Toast('新增地址');
      this.$router.push({path:'/addAddress'})
    },
    goBack(){
      this.$router.go(-1)
    },

    async getAddressListData(){
      const res = await getAddressList()
      if(res.status === 200){
        this.oldList = res.data.data
        let addressData = res.data.data
        let newAddressData = []
        addressData.forEach((item) =>{
          let addressItem = {
            id:item.id,
            name:item.name,
            tel:item.phone,
            address:item.province + item.city + item.county + item.address,
            isDefault:item.is_default === 1
          }
          newAddressData.push(addressItem)
          this.list = [...new Set(newAddressData)]
          this.chosenAddressId = this.list[0].id
        })
      }
      // this.list = new Set(this.list)
      console.log(res);
    },
    onEdit(item, index) {
      Toast('编辑地址:' + index);
      console.log(this.oldList[index]);
      this.$router.push({name:'editAddress',params:{addressInfo:this.oldList[index]}})
    },
    //删除地址
    deleteAddress(){
      Dialog.confirm({
        title: '地址删除确认',
        message: '是否要删除当前地址',
        theme: 'round-button',
      }).then(async () => {
        const res = await deleteAddress(this.chosenAddressId)
        if(res.status === 204){
          Toast.success('删除成功')
          await this.getAddressListData()
        }
        console.log(res);
      }).catch(()=>{
        console.log('取消删除');
      });
      console.log(this.chosenAddressId);
    },

  },
}
</script>

<style scoped lang="css">
.address-container{
  height: 100%;
  background-color: #eee;
}
.address-content{
  padding-top: 45px;
}
.left{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.iconfont{
  font-size: 24px;
}
.van-button{
  background-color: #42bBaa;
  border: none;
}
.delete-icon{
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>
